﻿using UnityEngine;
using System.Collections;

public class EnemyMove : MonoBehaviour {

    public Transform player;

    public float attackDist = 10;

    private Animator anim;

    public float speed = 2;

    /// <summary>
    /// 头顶，用于检测敌人是否被踩死
    /// </summary>
    public EnemyTop top = null;

    void Awake()
    {
        anim = this.GetComponent<Animator>();
    }
    
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {

        if (top.isDead == false)
        {
            if (Vector3.Distance(player.position, transform.position) < attackDist)
            {
                anim.SetBool("Run", true);

                //控制敌人的转向
                if (player.position.x < transform.position.x)
                {
                    transform.localScale = new Vector3(-1, 1, 1);
                }
                else
                {
                    transform.localScale = new Vector3(1, 1, 1);
                }

                //控制追击
                Vector3 dir = player.position - transform.position;
                transform.position += dir.normalized * speed * Time.deltaTime;
            }
            else
            {
                anim.SetBool("Run", false);
            }
        }
        else
        {
            anim.SetBool("Dead", true);
            PlayManager.Instance.PlayEnemyDies();
            Object.DestroyObject(transform.gameObject, 0.5f);
        }
	}
}
